<template>
  <div
    class="video-recorder"
    :style="`width:${width}px;min-height:${height}px;`"
  >
    <video
      :width="width"
      :height="height"
      controls="true"
      autoplay="true"
      id="video"
      :src="videoUrl"
    ></video>
    <div class="f-r-a-c" style="margin: 10px 0">
      <button v-show="isRecording" class="btn" @click="stopRecord">结束</button>
      <button v-show="!isRecording" class="btn" @click="startRecord">
        开始
      </button>
    </div>
  </div>
</template>

<script>
import { onMounted, inject, ref, reactive } from "vue";
export default {
  name: "videoRecorder",
  components: {},
  props: {
    videoId: String,
    width: Number | String,
    height: Number | String,
  },
  setup(props, context) {
    const { videoId } = props;
    let recorder = null;
    let videoUrl = ref("");
    let isRecording = ref(false);
    const startRecord = () => {
      videoUrl.value = "";
      const video = document.getElementById(videoId);
      const stream = video.captureStream(30);

      let mimeType = "video/webm";
      if (!MediaRecorder.isTypeSupported(mimeType)) {
        mimeType = "video/mp4";
      }
      recorder = new MediaRecorder(stream, { mimeType });

      const chunks = [];
      recorder.ondataavailable = function (event) {
        if (event.data) {
          chunks.push(event.data);
        }
      };

      recorder.onstop = () => {
        const videoBlob = new Blob(chunks, { type: mimeType }); // 创建视频文件
        const url = URL.createObjectURL(videoBlob);
        videoUrl.value = url;
        saveMp4(url);
        saveWebm(url);
      };

      recorder.start();
      isRecording.value = true;
    };

    const stopRecord = () => {
      recorder.stop();
      isRecording.value = false;
    };

    const saveMp4 = (url) => {
      var tag = document.createElement("a");
      tag.href = url;
      tag.download = `video_recorder_${+new Date()}.mp4`;
      document.body.appendChild(tag);
      tag.click();
      document.body.removeChild(tag);
    };

    // webm->mp4 转换链接 https://convertio.co/zh/download/c6718cb93ff39a6fbac2e53d7add591d41fa96/
    const saveWebm = (url) => {
      var tag = document.createElement("a");
      tag.href = url;
      tag.download = `video_recorder_${+new Date()}.webm`;
      document.body.appendChild(tag);
      tag.click();
      document.body.removeChild(tag);
    };

    return { videoUrl, isRecording, startRecord, stopRecord };
  },
};
</script>
<style lang="less" scoped>
.video-recorder {
  border: solid 1px black;
  border-radius: 8px;
}
</style>